package com.icart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icart.WxTemplate.TemplateData;
import com.icart.WxTemplate.WxTemplate;
import com.icart.comm.AjaxRspResult;
import com.icart.context.HttpUserContext;
import com.icart.context.storage.ContextStorage;
import com.icart.context.storage.SessionContextStorageImpl;
import com.icart.repositories.CustcarRepository;
import com.icart.repositories.ServbookRepository;
import com.icart.repositories.ServbookitemRepository;
import com.icart.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class ShopdetailController {

    @Autowired
    HttpServletRequest request;
    @Autowired
    private ServbookRepository ServbookRepository;
    @Autowired
    private ServbookitemRepository ServbookitemRepository;
    @Autowired
    private CustcarRepository custcarRepository;
    @Autowired
    HttpSession session;
    @Autowired
    private RestTemplate template;

    @RequestMapping("/shopdetail")
    public String shopdetail(Model model) {
        Long chnid=Long.parseLong(request.getParameter("chnid"));
        Object lat=session.getAttribute("lat");//纬度
        Object lon=session.getAttribute("lon");//经度
        String path="shop/shopdetail";//跳转路径
        //商店信息
        String shopsql="select bc.chnid,bc.chnname,bc.addr,bc.tel,bc.beginworktime,bc.endworktime,bc.isbook,bc.lat,bc.lon," +
                "(select AVG(wc.commstar) from wo_comment wc where  wc.oid in(select oid from wo_info where chnid=bc.chnid))com," +
                "(select count(*) from wo_info w where w.stat not in(-1) and w.chnid=bc.chnid)num," +
                "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( "+lat+" * PI() / 180 - bc.lat * PI() / 180) / 2),2) + COS("+lat+" * PI() / 180) * COS(bc.lat * PI() / 180) * POW(SIN((" + lon+" * PI() / 180 - bc.lon * PI() / 180) / 2 ),2)))*10) AS distance" +
                " from bi_chn bc where bc.chnid="+chnid;
        String picsql="select picurl from bi_chnpic where isdefault not in(1) and chnid="+chnid;

        //服务技师
        String servsql="select bs.staffid,bs.staffname,(select count(*) from wo_info w where w.stat not in(-1) and w.chnid=bs.chnid and w.servman=bs.staffid)num," +
                "(select AVG(wc.commstar) from wo_commentitem wc where wc.objid=bs.staffid and wc.itemid in(select itemid from wo_commentdef where itemtype='serv'))com " +
                "from bi_chnstaff bs where bs.status=1 and bs.post='service' and bs.chnid="+chnid;
        String sernum="select count(bs.staffid)servnum from bi_chnstaff bs where bs.post='service' and bs.chnid="+chnid;

        //服务项目+所属分组
        String sql="select bsp.packid,bs.servitemid,bs.servitemname,(select whprice from bi_servitemprice where chnid="+chnid+" and carkindid=0 and servitemid=bs.servitemid)whprice " +
                "from bi_servitem bs,bi_servpackitem bspi,bi_servpack bsp " +
                "where bsp.packid=bspi.packid and bs.servitemid=bspi.servitemid and " +
                "bs.servitemid in(select bss.servitemid from bi_servitem bss where bss.isbook=1 and bss.chnid="+chnid+" union select bsc.servitemid from bi_servitemchn bsc where bsc.chnid="+chnid+" and bsc.stat=1)";

        String itnum="select count(bs.servitemid)itemnum from bi_servitem bs where " +
                "bs.servitemid in(select bss.servitemid from bi_servitem bss where bss.isbook=1 and bss.chnid="+chnid+" union select bsc.servitemid from bi_servitemchn bsc where bsc.chnid="+chnid+" and bsc.stat=1)";

        //根据服务项目查找对应的分组(用于展示分组和匹配服务项目)
        String sql1="select DISTINCT bsp.* from bi_servitem bs,bi_servpackitem bspi,bi_servpack bsp " +
                "where bsp.packid=bspi.packid and bs.servitemid=bspi.servitemid and " +
                "bs.servitemid in(select bss.servitemid from bi_servitem bss where bss.isbook=1 and bss.chnid="+chnid+" union select bsc.servitemid from bi_servitemchn bsc where bsc.chnid="+chnid+" and bsc.stat=1)";

        //根据服务项目查出的分组查询对应的分组归属(用于匹配数据，没有展示的数据)
        String sql2="select DISTINCT bspb.* from bi_servitem bs,bi_servpackitem bspi,bi_servpackbelong bspb " +
                "where bs.servitemid=bspi.servitemid and bspi.packid=bspb.packid and " +
                "bs.servitemid in(select bss.servitemid from bi_servitem bss where bss.isbook=1 and bss.chnid="+chnid+" union select bsc.servitemid from bi_servitemchn bsc where bsc.chnid="+chnid+" and bsc.stat=1)";

        //查询所有的分组归属(用于展示)
        String sql3="select DISTINCT(bspb.belongcode),sa.dictname " +
                "from bi_servitem bs,bi_servpackitem bspi,bi_servpackbelong bspb,sa_db_dictitem sa " +
                "where bs.servitemid=bspi.servitemid and bspi.packid=bspb.packid and " +
                "bs.servitemid in(select bss.servitemid from bi_servitem bss where bss.isbook=1 and bss.chnid="+chnid+" union select bsc.servitemid from bi_servitemchn bsc where bsc.chnid="+chnid+" and bsc.stat=1) " +
                "and sa.dictid=bspb.belongcode and sa.groupid='BI_SERVPACKBELONG'";

        //评论(选两条)
        String comsql="select (select custname from cu_custinfo where custid=wo.custid)custname,wc.commstar,wc.commcontent,wc.createtime,wc.isanonymous," +
                "(select carlinename from bi_carline where carlineid=bc.carlineid)carlinename,(select carfactname from bi_carfactory where carfactid=(select carfactid from bi_carline where carlineid=bc.carlineid))carfactname," +
                "(select servitemname from bi_servitem where servitemid=(select servitemid from wo_infoserv where oid=wo.oid limit 0,1))servitemname" +
                " from wo_comment wc,wo_info wo,cu_custcar cc,bi_cardef bc where wc.ispic=0 and cc.setdefault=1 and bc.cartypeid=cc.cartype and cc.custid=wo.custid and wc.oid=wo.oid and wo.chnid="+chnid+" order by wc.commstar desc,wc.createtime desc limit 0,2";

        //跳转至不可预约的门店页面
        if(Tools.notEmpty(request.getParameter("flag"))){
            path="shop/shopdet";
        } else {
            //加载用户车型等信息
            ContextStorage storage=new SessionContextStorageImpl(request);
            HttpUserContext userContext=storage.getUserContext("loginuser");
            if(userContext!=null) {
                Long custid=userContext.getCustid();
                String custcarsql = "select cc.custid,cc.curkilo,cc.regdate,bc.carvol,bc.caryear,cc.carno,cc.custcarid,(select brandlogo from bi_carbrand where brandid=bc.brandid)brandlogo," +
                        "(select carlinename from bi_carline where carlineid=bc.carlineid)carlinename,(select carfactname from bi_carfactory where carfactid=(select carfactid from bi_carline where carlineid=bc.carlineid))carfactname" +
                        " from cu_custcar cc,bi_cardef bc where cc.setdefault=1 and bc.cartypeid=cc.cartype and cc.custid=" + custid;
                List custcar = custcarRepository.createNativeQuery(custcarsql);
                if(custcar.size()!=0){
                    model.addAttribute("custcar",custcar.get(0));
                } else{
                    model.addAttribute("custid",custid);
                }
            }
        }

        List list = ServbookRepository.createNativeQuery(sql);
        List servnum = ServbookRepository.createNativeQuery(sernum);
        List itemnum = ServbookRepository.createNativeQuery(itnum);
        List list1 = ServbookRepository.createNativeQuery(sql1);
        List list2 = ServbookRepository.createNativeQuery(sql2);
        List list3 = ServbookRepository.createNativeQuery(sql3);
        List com = ServbookRepository.createNativeQuery(comsql);
        List servlist=ServbookRepository.createNativeQuery(servsql);
        List shop=ServbookRepository.createNativeQuery(shopsql);
        List pic=ServbookRepository.createNativeQuery(picsql);

        String url="http://pay.wechat.ikartek.com/jssdk/api.php?url=http://testwx.ikartek.com/shopdetail?chnid="+chnid+"&token=";
        HomeController.gettoken(model,template,url,request);

        model.addAttribute("list",list);
        model.addAttribute("itemnum",itemnum.get(0));
        model.addAttribute("servnum",servnum.get(0));
        model.addAttribute("list1",list1);
        model.addAttribute("list2",list2);
        model.addAttribute("list3",list3);
        model.addAttribute("shop",shop.get(0));//门店
        model.addAttribute("pic",pic);//图片
        model.addAttribute("servlist",servlist);//服务顾问
        model.addAttribute("com",com);//评价
        return path;
    }

    @RequestMapping(value = "/shopdetailtime",method = RequestMethod.GET)
    @ResponseBody
    public List<String> data() {
        List<String> list = new ArrayList<String>();
        int st=-1;
        int end=14;
        list.add(returnDate(st));
        list.add(returnDate(end));
        return list;
    }
    //通过当前日期获得未来的日期
    private String returnDate(int count) {
        Calendar strDate = Calendar.getInstance();
        strDate.add(strDate.DATE, count);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(strDate.getTime());
    }

    @RequestMapping(value = "/shopdetailorder",method = RequestMethod.POST)
    @ResponseBody
    public AjaxRspResult shoporder() {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");
        Long custid=userContext.getCustid();
        String sql="select cc.custcarid,cc.carno,c.custname,c.mobile from cu_custinfo c,cu_custcar cc where cc.setdefault=1 and cc.custid=c.custid and c.custid="+custid;
        List cust=ServbookRepository.createNativeQuery(sql);
        System.out.print(cust);
        String cust2 = JSON.toJSONString(cust);
        cust2=cust2.replace("[", "");
        cust2=cust2.replace("]", "");
        System.out.print(cust2);
        JSONObject cust3 = JSON.parseObject(cust2);//将list转换为json对象

        String shop=request.getParameter("shop");
        JSONObject jsonObject= JSON.parseObject(shop);
        System.out.println(jsonObject);

        String regdate=jsonObject.getString("cardate");//上路时间
        String shoplist0=jsonObject.getString("shoplist");
        String[] shoplist=shoplist0.split(",");

        String bus= shoplist[1];
        List busi=ServbookRepository.createNativeQuery("select busiid from bi_servitem where servitemid="+bus);
        String busii = JSON.toJSONString(busi);
        busii=busii.replace("[", "");
        busii=busii.replace("]", "");
        JSONObject busiid = JSON.parseObject(busii);

        Date dates=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creattime=format.format(dates);//获取当前系统时间
        Long times=dates.getTime();//获取当前系统时间,暂时用作预约流水号
        Long custcarid=Long.parseLong(cust3.getString("custcarid"));
        String carno=cust3.getString("carno");
        Long curkilo=Long.parseLong(jsonObject.getString("km"));//里程
        String linkman=cust3.getString("custname");
        String linktel=cust3.getString("mobile");
        Long busiid2=Long.parseLong(busiid.getString("busiid"));//业务分类
        Long chnid=Long.parseLong(jsonObject.getString("shopid"));//门店
        String date=jsonObject.getString("date");//预约日期
        String time=jsonObject.getString("time");//预约时间
        String bookcode=ShopController.bookcode();
        Long servid=jsonObject.getString("servid")==null?0:Long.parseLong(jsonObject.getString("servid"));//预约顾问
        Integer f=ServbookRepository.insert(times,custid,custcarid,carno,curkilo,regdate,linkman,linktel,busiid2,chnid,date,time,servid,creattime,0,bookcode);

        Long packid=0L;
        int cnt;
        Long servitemid=0L;
        int flag=0;
        for(int i=0;i<shoplist.length;i++){
            if(flag==0){
                packid=Long.parseLong(shoplist[i]);
            }
            if(flag==1){
                servitemid=Long.parseLong(shoplist[i]);
            }
            if(flag==2){
                cnt=Integer.parseInt(shoplist[i]);
                ServbookitemRepository.insert(times,servitemid,cnt,packid,busiid2);
                flag=0;
                continue;
            }
            flag++;
        }

        //发送模板消息
        String chnname=jsonObject.getString("chnname");//门店名称
        String shoptel=jsonObject.getString("shoptel");//联系方式

        WxTemplate wxtemplate=new WxTemplate();
        String openid=request.getSession().getAttribute("openid").toString();
        wxtemplate.setTouser(openid);//用户的OPENID
        wxtemplate.setTopcolor("#000000");
        wxtemplate.setTemplate_id("h-MqpqoU3jNfI6GozAFu7tjAt4Lfdoaeps0yWv2MmDs");
        Map<String,TemplateData> m = new HashMap<String,TemplateData>();
        TemplateData first = new TemplateData();
        first.setColor("#000000");
        first.setValue("尊敬的"+carno+"车主，您的预约已提交成功，请耐心等待门店确认");
        m.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setColor("#173177");
        keyword1.setValue(date+" "+time);//预约时间
        m.put("keyword1", keyword1);
        TemplateData keyword2 = new TemplateData();
        keyword2.setColor("#173177");
        keyword2.setValue(chnname);//预约门店
        m.put("keyword2", keyword2);
        TemplateData keyword3 = new TemplateData();
        keyword3.setColor("#173177");
        keyword3.setValue(shoptel);//联系方式
        m.put("keyword3", keyword3);
        TemplateData remark = new TemplateData();
        remark.setColor("#000000");
        remark.setValue("如有疑问请通过联系方式联系门店，谢谢!");
        m.put("remark", remark);
        wxtemplate.setData(m);
        String data = JSONObject.toJSONString(wxtemplate).toString();
        WxUtilController w=new WxUtilController();
        w.sendMessage(data,template,request);

        AjaxRspResult arr=new AjaxRspResult();
        return arr;
    }

    @RequestMapping(value = "/shopdetailbooktime",method = RequestMethod.GET)
    @ResponseBody
    public AjaxRspResult booktime(@RequestParam(name = "chnid",required = false) String chnid,@RequestParam(name = "bookdate",required = false) String bookdate) {
        String sql="select workcount,beginworktime,endworktime from bi_chn where chnid="+chnid;
        List list=ServbookRepository.createNativeQuery(sql);
        String chn = JSON.toJSONString(list);
        chn=chn.replace("[", "");
        chn=chn.replace("]", "");
        JSONObject chn2 = JSON.parseObject(chn);

        String beginworktime=chn2.getString("beginworktime");
        String endworktime=chn2.getString("endworktime");
        String workcount=chn2.getString("workcount");//工位数
        String[] time1=beginworktime.split(":");
        String[] time2=endworktime.split(":");
        int hb=Integer.parseInt(time1[0]);
        int mb=Integer.parseInt(time1[1]);
        int he=Integer.parseInt(time2[0]);
        int me=Integer.parseInt(time2[1]);

        String sql2="select w.booktime from wo_servbook w " +
                "where w.stat not in(-1) and w.chnid="+chnid+" and w.bookdate='"+bookdate+"' and " +
                "(select count(*) from wo_servbook where chnid="+chnid+" and bookdate='"+bookdate+"' and booktime=w.booktime)>="+workcount+" GROUP BY w.booktime";
        List list2=ServbookRepository.createNativeQuery(sql2);//查找超出门店工位数的预约时间段
        String rep=list2.toString();
        rep=rep.replace("{","");
        rep=rep.replace("}","");
        rep=rep.replace("booktime=","");
        rep=rep.replace(" ","");

        //判断预约日期是否为今天
        Date dates=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        String systime=format.format(dates);//获取当前系统时间
        boolean ff=true;
        if(bookdate.equals(systime)){
            Calendar c = Calendar.getInstance();
            int hour=c.get(Calendar.HOUR_OF_DAY);//得到现在的时间
            if(hour+1>=he){
                ff=false;
            } else {
                if(hour<=hb){

                } else {
                    hb=hour+1;
                }
            }
        }
        List<String> booktime = new ArrayList<String>();
        while(ff){
            String min="00";
            String t="";
            if(mb==0){
                t+=hb+":"+min;
            } else {
                t+=hb+":"+mb;
            }
            mb+=30;
            if(mb>=60){
                mb=mb-60;
                hb++;
            }
            if(mb==0){
                t+="-"+hb+":"+min;
            } else {
                t+="-"+hb+":"+mb;
            }
            booktime.add(t);
            if(hb>he||(hb==he&&mb>me)){
                break;
            }
        }
        List listtotal=new ArrayList();
        listtotal.add(booktime);
        listtotal.add(rep);
        AjaxRspResult arr=new AjaxRspResult();
        arr.setResult(listtotal);
        return arr;
    }

    @RequestMapping(value = "/shopdetailserv",method = RequestMethod.GET)
    public String shopserv(Model model) {
        String servid=request.getParameter("servid");
        String chnid=request.getParameter("chnid");
        String servsql="select (select chnname from bi_chn where chnid=bs.chnid)chnname,bs.staffid,bs.staffname,(select count(*) from wo_info w where w.chnid=bs.chnid and w.servman=bs.staffid)num," +
                "(select AVG(wc.commstar) from wo_commentitem wc where wc.objid=bs.staffid and wc.itemid in(select itemid from wo_commentdef where itemtype='serv'))com " +
                "from bi_chnstaff bs where bs.status=1 and bs.post='service' and bs.chnid="+chnid+" and bs.staffid="+servid;
        List serv=ServbookRepository.createNativeQuery(servsql);
        //评价
        String comsql="select (select custname from cu_custinfo where custid=wt.custid)custname,wt.isanonymous,wc.commid,wc.commstar,wc.commcontent,wt.createtime," +
                "(select cartypename from bi_cardef where cartypeid=wo.cartype)cartypename,(select servitemname from bi_servitem where servitemid=(select servitemid from wo_infoserv where oid=wo.oid limit 0,1))servitemname " +
                "from wo_commentitem wc,wo_comment wt,wo_info wo " +
                "where wo.oid=wc.oid and wt.commid=wc.commid and wc.objid="+servid+" and wc.itemid in(select itemid from wo_commentdef where itemtype='serv') order by wt.createtime desc";
        //评价图片
        String picsql="select * from wo_commentpic,wo_commentitem wc where wc.objid="+servid+" and wc.itemid in(select itemid from wo_commentdef where itemtype='serv')";
        List com=ServbookRepository.createNativeQuery(comsql);
        model.addAttribute("serv",serv.get(0));
        model.addAttribute("com",com);
        return "shop/shopserv";
    }

    @RequestMapping(value = "/shopcom",method = RequestMethod.GET)
    public String shopcom(Model model) {
        String chnid=request.getParameter("chnid");
        //评价
        String comsql="select wc.commid,(select custname from cu_custinfo where custid=wo.custid)custname,wc.commstar,wc.commcontent,wc.createtime,wc.isanonymous," +
                "(select carlinename from bi_carline where carlineid=bc.carlineid)carlinename,(select carfactname from bi_carfactory where carfactid=(select carfactid from bi_carline where carlineid=bc.carlineid))carfactname," +
                "(select servitemname from bi_servitem where servitemid=(select servitemid from wo_infoserv where oid=wo.oid limit 0,1))servitemname" +
                " from wo_comment wc,wo_info wo,cu_custcar cc,bi_cardef bc where cc.setdefault=1 and bc.cartypeid=cc.cartype and cc.custid=wo.custid and wc.oid=wo.oid and wo.chnid="+chnid+"  order by wc.commstar desc,wc.createtime desc";
        String comsql1="select wc.commid,(select custname from cu_custinfo where custid=wo.custid)custname,wc.commstar,wc.commcontent,wc.createtime,wc.isanonymous," +
                "(select carlinename from bi_carline where carlineid=bc.carlineid)carlinename,(select carfactname from bi_carfactory where carfactid=(select carfactid from bi_carline where carlineid=bc.carlineid))carfactname," +
                "(select servitemname from bi_servitem where servitemid=(select servitemid from wo_infoserv where oid=wo.oid limit 0,1))servitemname" +
                " from wo_comment wc,wo_info wo,cu_custcar cc,bi_cardef bc where cc.setdefault=1 and bc.cartypeid=cc.cartype and cc.custid=wo.custid and wc.oid=wo.oid and wo.chnid="+chnid+"  order by wc.createtime desc,wc.commstar desc";
        //评价图片
        String comsql2="select wc.commid,(select custname from cu_custinfo where custid=wo.custid)custname,wc.commstar,wc.commcontent,wc.createtime,wc.isanonymous," +
                "(select carlinename from bi_carline where carlineid=bc.carlineid)carlinename,(select carfactname from bi_carfactory where carfactid=(select carfactid from bi_carline where carlineid=bc.carlineid))carfactname," +
                "(select servitemname from bi_servitem where servitemid=(select servitemid from wo_infoserv where oid=wo.oid limit 0,1))servitemname" +
                " from wo_comment wc,wo_info wo,cu_custcar cc,bi_cardef bc where wc.ispic=1 and cc.setdefault=1 and bc.cartypeid=cc.cartype and cc.custid=wo.custid and wc.oid=wo.oid and wo.chnid="+chnid+"  order by wc.commstar desc,wc.createtime desc";
        String picsql="select w.* from wo_commentpic w,wo_commentitem wc where w.commid=wc.commid and wc.objid="+chnid+" and wc.itemid =3 ";
        //获得门店接待服务等评价分数
        String comsql3="select (select itemname from wo_commentdef where itemid=wc.itemid)itemname,AVG(wc.commstar)star from wo_commentitem wc where wc.oid in(select oid from wo_info where chnid="+chnid+") group by wc.itemid";
        List com=ServbookRepository.createNativeQuery(comsql);
        List com1=ServbookRepository.createNativeQuery(comsql1);
        List com2=ServbookRepository.createNativeQuery(comsql2);
        List pic=ServbookRepository.createNativeQuery(picsql);
        List com3=ServbookRepository.createNativeQuery(comsql3);
        model.addAttribute("com",com);
        model.addAttribute("com1",com1);
        model.addAttribute("com2",com2);
        model.addAttribute("com3",com3);
        model.addAttribute("chnid",chnid);
        model.addAttribute("pic",pic);
        return "shop/shopcom";
    }

}